<template>
  <div class="article">
    <!-- <link
      rel="stylesheet"
      href="https://apps.bdimg.com/libs/highlight.js/9.1.0/styles/monokai-sublime.min.css"
    /> -->

    <header class="h-[350px] relative">
      <img
        src="~/assets/images/article_default.png"
        class="h-full w-full object-cover relative z-[-1]"
        alt=""
      />
      <div class="absolute inset-0 flex flex-col bg-black bg-opacity-50">
        <div class="my-auto text-white mx-auto">
          <h1 class="text-white text-center text-[28px]">
            {{ articleInfo.title }}
          </h1>
          <div
            class="text-center mt-2 text-xs flex items-center justify-center"
          >
            <div class="text-base">
              <svg-icon icon-class="riqi" />
            </div>
            <span class="ml-2"
              >{{ $t('publishedOn') }} {{ articleInfo.create_time }}</span
            >
          </div>
          <div
            class="text-center mt-2 text-xs flex items-center justify-center"
          >
            <div class="text-base">
              <svg-icon icon-class="chakan" />
            </div>
            <span class="ml-2"
              >{{ $t('readingVolume') }} {{ articleInfo.view_count }}</span
            >
          </div>
        </div>
      </div>
    </header>
    <layouts-main>
      <Card>
        <md
          ref="md"
          :content="articleInfo.content"
          @onSelect="onSelect"
          @onScrollPercent="onScrollPercent"
        >
        </md>
      </Card>
      <Card class="mt-6" style="overflow: visible">
        <div class="flex justify-between items-center mb-3">
          <h3 class="text-base font-bold text-gray-700">
            {{ $t('comment.comment') }} {{ articleCommentCount }}
          </h3>
          <div class="flex gap-x-3 text-[24px]">
            <a
              class="cursor-pointer duration-300"
              @click.prevent="
                handleGo(
                  `https://github.com/login/oauth/authorize/?client_id=c8041d0aa048f60d86d7&redirect_uri=http://101.43.84.176:3000/oauth/github?redirect=${pageUrl}&scope=user:email`
                )
              "
            >
              <a-tooltip placement="bottom">
                <template slot="title">
                  <span>github {{ $t('comment.oauthLogin') }}</span>
                </template>
                <svg-icon icon-class="github" />
              </a-tooltip>
            </a>
            <a
              class="cursor-pointer duration-300"
              @click.prevent="
                handleGo(
                  `https://gitee.com/oauth/authorize?client_id=53cb01cc7fd633286a22b146bd2cca669fc8fbaaade01ac42f15827b095f786d&redirect_uri=http://101.43.84.176:3000/oauth/gitee?redirect=${pageUrl}&response_type=code&scope=user_info`
                )
              "
            >
              <a-tooltip placement="bottom">
                <template slot="title">
                  <span>gitee{{ $t('comment.oauthLogin') }}</span>
                </template>
                <svg-icon icon-class="gitee" />
              </a-tooltip>
            </a>
            <div class="cursor-pointer duration-300">
              <a-tooltip placement="bottom">
                <template slot="title">
                  <span>wechat{{ $t('comment.oauthLogin') }}</span>
                </template>
                <svg-icon icon-class="wechat" />
              </a-tooltip>
            </div>
            <div class="cursor-pointer duration-300">
              <a-tooltip placement="bottom">
                <template slot="title">
                  <span>QQ{{ $t('comment.oauthLogin') }}</span>
                </template>
                <svg-icon icon-class="QQ" />
              </a-tooltip>
            </div>
          </div>
        </div>
        <!-- 评论组件 -->
        <div class="flex">
          <div v-if="userInfo" class="text-gray-800 mr-2 cursor-pointer">
            <img
              class="w-[35px] h-[35px] rounded-full"
              :src="userInfo?.avatar"
              :alt="userInfo?.username"
            />
          </div>
          <comment-input
            class="flex-1"
            @onSubmit="handleSendComment"
          ></comment-input>
        </div>
        <!-- 评论组件 -->
        <comment-list :list="articleComments"></comment-list>
      </Card>

      <template #right>
        <user-card />
        <div class="sticky top-16 mb-6">
          <!-- 标题 -->
          <Card icon="menu" :title="$t('title')">
            <template #rt>
              <div class="text-[#00c4b6] text-[28px] italic">
                {{ scrollPercent }}
              </div>
            </template>
            <div ref="total-wrapper" class="mb-4 max-h-[35vh] overflow-y-auto">
              <ul class="">
                <li
                  v-for="(articleTitle, index) in articleTitles"
                  :key="index"
                  class="w-full py-1 px-2 hover:bg-[#f8f8f8] border-l-2 mb-0.5 border-transparent text-[#4c4948]"
                  :class="{
                    select: index === select,
                    [articleTitle.tagName]: true,
                  }"
                  @click="handleSelect(index)"
                >
                  <div
                    class="text-xs leading-6 w-full cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis"
                  >
                    {{ articleTitle.title }}
                  </div>
                </li>
              </ul>
            </div>
          </Card>
          <Card
            class="sticky mt-4"
            icon="wenzhang1"
            :title="$t('latestArticles')"
          >
            <div
              v-for="lastNewArticle in lastNewArticles"
              :key="lastNewArticle.id"
              class="flex mb-4"
            >
              <div class="w-[50px] h-[50px]">
                <img
                  src="~/assets/images/article_default.png"
                  alt="article_default"
                  class="w-full h-full block object-cover"
                />
              </div>
              <div class="flex-1 w-0 ml-3">
                <nuxt-link
                  :to="localePath(`/article/${lastNewArticle.id}`)"
                  class="w-full text-xs text-gray-700 hover:text-blue-500 duration-300 cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis"
                >
                  {{ lastNewArticle.title }}
                </nuxt-link>
                <div
                  class="text-xs text-gray-400 mt-1 w-full cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis"
                >
                  {{ lastNewArticle.create_time }}
                </div>
              </div>
            </div>
          </Card>

          <Card class="sticky mb-4 mt-6" icon="biaoqian" :title="$t('tags')">
            <div class="flex flex-wrap gap-x-3 gap-y-2">
              <nuxt-link
                v-for="tag in tags"
                :key="tag.id"
                class="text-base text-gray-400"
                :class="{
                  '!text-blue-400 !text-lg': articleInfo?.tags?.find?.(
                    (one) => one.id === tag.id
                  ),
                }"
                :to="localePath(`/tags/${tag.id}`)"
              >
                <div>{{ tag.name }}</div>
              </nuxt-link>
            </div>
          </Card>
        </div>
      </template>
    </layouts-main>
  </div>
</template>

<script>
import { gsap } from 'gsap'
import previewImage from '@/utils/preview-image'
export default {
  name: 'ArticlesId',

  async asyncData(context) {
    const { data } = await context.$apis.client.articleByIdPage(context.params)
    return {
      articleInfo: data.articleInfo,
      lastNewArticles: data.lastNewArticles,
      tagNum: data.tagNum,
      articleFiles: data.articleFiles,
      tags: data.tags,
      articleTitles: data.articleTitles,
      articleComments: data.articleComments,
      articleCommentCount: data.articleCommentCount,
      user: data.user,
    }
  },

  data() {
    return {
      select: 0, // 选中的索引
      scrollTops: [], // 每个标题滚动到中间需要滚动的量
      scrollPercent: 0, // 滚动百分比
      pageUrl: globalThis?.location?.href || '',
    }
  },
  head() {
    return {
      script: [
        {
          charset: 'utf-8',
          src: '/js/bg-canvas.js',
          body: true,
        },
      ],
      link: [
        {
          rel: 'stylesheet',
          href: 'https://apps.bdimg.com/libs/highlight.js/9.1.0/styles/monokai-sublime.min.css',
        },
      ],
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo
    },
  },
  watch: {
    select: {
      handler(index) {
        if (this.scrollTops.length < 0 || !this.$refs['total-wrapper'])
          return false
        const scrollTop = this.scrollTops[index]
        this.$refs['total-wrapper'].scrollTop = scrollTop
      },
      immediate: true,
    },
  },

  mounted() {
    this.initCalc()
    this.previewImage()
  },
  methods: {
    handleSelect(index) {
      const mdInstance = this.$refs.md
      if (!mdInstance) return false
      const info = mdInstance.titles[index]
      const html = document.documentElement

      gsap.to(html, {
        scrollTop: info?.top - 80,
        duration: 0.5, // 持续时间
      })
    },
    onSelect(index) {
      this.select = index
    },
    initCalc() {
      // 在这里获取每个标题 在中间显示，需要滚动的距离；
      // 需要滚动的距离 = 距离顶部的高度 - 父容器距离顶部的高度 - 父容器高度的一半
      const lis = Array.from(
        this.$refs['total-wrapper'].querySelectorAll('ul>li')
      )
      const wrapper = this.$refs['total-wrapper']
      const rect = wrapper.getBoundingClientRect()
      this.scrollTops = lis.map(
        (el) => el.getBoundingClientRect().top - rect.top - rect.height / 2
      )
    },
    // // 获取titles
    // async onGetTitle(titles) {
    //   this.titles = titles

    //   await this.$nextTick()
    //   // 在这里获取每个标题 在中间显示，需要滚动的距离；
    //   // 需要滚动的距离 = 距离顶部的高度 - 父容器距离顶部的高度 - 父容器高度的一半
    //   const lis = Array.from(
    //     this.$refs['total-wrapper'].querySelectorAll('ul>li')
    //   )
    //   const wrapper = this.$refs['total-wrapper']
    //   const rect = wrapper.getBoundingClientRect()
    //   this.scrollTops = lis.map(
    //     (el) => el.getBoundingClientRect().top - rect.top - rect.height / 2
    //   )
    // },
    // 获取滚动百分比
    onScrollPercent(scrollPercent) {
      this.scrollPercent = scrollPercent
    },
    // 文章评论
    async handleSendComment({ file, content }) {
      if (!this.userInfo) {
        return this.$warning({
          title: '请先登录后再进行评论~',
        })
      }
      if (!file && !content) {
        return this.$warning({
          title: '评论内容不能为空~',
        })
      }
      const { code } = await this.$apis.client.inserArticleComment({
        file,
        content,
        articleId: this.articleInfo.id,
        userId: this.userInfo?.id,
      })
      if (code === 200) {
        this.$success({
          title: '评论成功~',
          onOk: () => {
            window.location.reload()
          },
        })
      }
    },
    previewImage() {
      Array.from(document.querySelectorAll('#md img, .comment-image')).forEach(
        (el) => {
          el.addEventListener('click', () => {
            previewImage(el)
          })
        }
      )
    },
    handleGo(url) {
      window.location.href = url
    },
  },
}
</script>
<style lang="scss" scoped>
.article {
  header {
    animation: SlideDown 0.52s ease-in-out 0s;
  }
  main {
    animation: SlideUp 0.52s ease-in-out 0s;
  }
  .select {
    background-color: #00c4b6;
    border-color: #009d92;
    color: #ffffff;
  }
}

@keyframes SlideDown {
  0% {
    transform: translateY(-30px);
    opacity: 0.5;
  }
  100% {
    transform: translateY(0px);
    opacity: 1;
  }
}

@keyframes SlideUp {
  0% {
    transform: translateY(30px);
    opacity: 0.5;
  }
  100% {
    transform: translateY(0px);
    opacity: 1;
  }
}
</style>
